package com.realgodo.site.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**		
 * @author 		
 * @version 创建时间：2009-6-10下午02:46:23	
 * 类说明 copy自 mini项目 期待复用
 */
public class FileUpload {
	private static final Log log = LogFactory.getLog(FileUpload.class);

	public static String getFileName(String fileName){
		String fileType = fileName.substring(fileName.lastIndexOf("."));
		return new SimpleDateFormat("yyyyMMddHHmmssSSS"+(int) (Math.random()*100)).format(Calendar.getInstance().getTime())+fileType;
	}
	
	public static String saveFile(String fileName, File file) {
		File fp = new File(getFilePath(fileName));
		if(!fp.exists()){
			fp.mkdirs();
		}
		
		File tempFile = new File(fileName);
		try {
			FileInputStream fis = new FileInputStream(file);
			FileOutputStream fos = new FileOutputStream(tempFile);
			int index = 0;
			try {
				while ((index = fis.read()) != -1) {
					fos.write(index);
				}
			} catch (IOException ie) {
				log.error(ie);
			} finally {
				fis.close();
				fos.close();
			}
			return tempFile.getName();
			

		} catch (FileNotFoundException fnfe) {
			log.error(fnfe);
		} catch (IOException ioe) {
			log.error(ioe);
		}

		return null;
	}
	
	public static String getFilePath(String fileName){
		int len = fileName.length();
		if(fileName!=null&&len>0){
			int index = fileName.lastIndexOf("\\");
			if (index == -1) index = fileName.lastIndexOf("/");
			if(index>0&&index<len){
				return fileName.substring(0, index);
			}
		}
		return fileName;
	}
}
